package com.crayfish.quduo.http;

import com.crayfish.quduo.commom.Configs;
import com.crayfish.quduo.commom.Constants;
import com.crayfish.quduo.model.JokeItemBean;
import com.crayfish.quduo.model.LaiFuDaoBean;
import com.crayfish.quduo.model.MeipaiBean;
import com.crayfish.quduo.model.TianXinBean;
import com.crayfish.quduo.utils.SystemUtil;
import com.google.gson.Gson;

import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Observable;

/**
 * Created by crayfish on 2016/12/5.
 *
 */
public class RetrofitHelper {
    private static OkHttpClient okHttpClient = null;
    private static YoukuApis youkuApisService = null;
    private static MeipaiApis meipaiApis = null;
    private static TianXinApis tianXinApis = null;
    private static LaiFuDaoApis laiFuDaoApis = null;
    private static JokeApis jokeApis = null;

    public RetrofitHelper(){
        init();
//        youkuApisService = getYoukuApiService();
        meipaiApis = getMeipaiApiService();
        tianXinApis = getTianXinApiService();
        laiFuDaoApis = getLaiFuDaoApiService();
        jokeApis = getJokeApiService();
    }

    public void init(){
        initOkHttp();
    }

    public void initOkHttp(){
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        if(Configs.DEBUG){
            HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
            loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BASIC);
            builder.addInterceptor(loggingInterceptor);
        }
        File cacheFile= new File(Constants.PATH_CACHE);
        Cache cache = new Cache(cacheFile,1024*1024*50);
        Interceptor interceptor = new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request request = chain.request();
                if(SystemUtil.isNetWorkConnected()){
                    request = request.newBuilder()
//                            .addHeader("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0")
//                            .addHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
//                            .addHeader("Accept-Language","zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3")
//                            .addHeader("Host","api.laifudao.com")
//                            .cacheControl(CacheControl.FORCE_CACHE)
                            .build();
                }
                Response response = chain.proceed(request);
                if(SystemUtil.isNetWorkConnected()){
                    int maxAge = 0;
                    //有网络时，不缓存，最大保存时长为0
                    response.newBuilder()
                            .header("Cache-Control","public, max-age="+maxAge)
                            .removeHeader("Pragma")
                            .build();
                }else{
                    //无网络时，设置超时为4周
                    int maxStale = 60*60*24*28;
                    response.newBuilder()
                            .header("CaChe-Control","public, only-if-cached, max-stale="+maxStale)
                            .removeHeader("Pragma")
                            .build();

                }
                return response;
            }
        };
        //设置缓存
        builder.addNetworkInterceptor(interceptor);
        builder.addInterceptor(interceptor);
        builder.cache(cache);
        //设置超时
        builder.connectTimeout(10, TimeUnit.SECONDS);
        builder.readTimeout(20,TimeUnit.SECONDS);
        builder.writeTimeout(20,TimeUnit.SECONDS);
        //错误重连
        builder.retryOnConnectionFailure(true);
        okHttpClient = builder.build();
    }

    private static YoukuApis getYoukuApiService(){
        Retrofit youkuRetrofit = new Retrofit.Builder()
                .baseUrl(YoukuApis.HOST)
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();
        return youkuRetrofit.create(YoukuApis.class);
    }

    private static MeipaiApis getMeipaiApiService(){
        Retrofit meipaiRetrofit = new Retrofit.Builder()
                .baseUrl(MeipaiApis.HOST)
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();
        return meipaiRetrofit.create(MeipaiApis.class);
    }

    private static TianXinApis getTianXinApiService(){
        Retrofit tianxinRetrofit = new Retrofit.Builder()
                .baseUrl(TianXinApis.HOST)
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();
        return tianxinRetrofit.create(TianXinApis.class);
    }

    private static LaiFuDaoApis getLaiFuDaoApiService(){
        Retrofit lfdRetrofit = new Retrofit.Builder()
                .baseUrl(LaiFuDaoApis.HOST)
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();
        return lfdRetrofit.create(LaiFuDaoApis.class);
    }

    private static JokeApis getJokeApiService(){
        Retrofit jokeRetrofit = new Retrofit.Builder()
                .baseUrl(JokeApis.HOST)
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();
        return jokeRetrofit.create(JokeApis.class);
    }

    public Observable<List<MeipaiBean>> getMeipaiList(String id){
        return meipaiApis.getMeipaiList(id);
    }

    public Observable<TianXinResponse<List<TianXinBean>>> getMeinvList(String num,String page){
        return tianXinApis.getMeinvList(Configs.TX_KEY,num,page,"1");
    }

    public Observable<List<LaiFuDaoBean>> getTupianList(){
        return laiFuDaoApis.getTupianList();
    }

    public Observable<JokeItemResponse<JokeItemBean>> getJokeList(String page, String num, String time){
        return jokeApis.getJokeList("30371",Configs.JOKE_KEY,page,num,time);
    }
}
